<template>
  <!-- 口径层级页面 -->
  <div>
    <el-row class="caliberHierarchy container" :gutter="20">
      <el-col :span="24">
        <!-- 操作区域 -->
        <upper-template
          @search="searchForm.page=1,searchFunc()"
          @clear="
            (searchForm.ruleCode = ''),
              (searchForm.ruleName = ''),
              (searchForm.driverType = ''),
              (searchForm.ruleType = '')
          "
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea">
            <el-button @click="addFunc">新增</el-button>
            <el-button @click="editFunc">编辑</el-button>
            <el-button @click="deleteFunc">删除</el-button>
            <el-button @click="viewFunc">查看</el-button>
            <el-button @click="copyView">复制</el-button>
            <el-button @click="running">运行</el-button>
          </template>
          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="100px"
              label-position="left"
              size="mini"
            >
              <el-form-item label="编码：">
                <el-input
                  v-model.trim="searchForm.ruleCode"
                  placeholder="请输入编码"
                ></el-input>
              </el-form-item>
              <el-form-item label="名称：" prop="ruleName">
                <el-input
                  v-model.trim="searchForm.ruleName"
                  placeholder="请输入名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="规则类型：">
                <el-select
                  v-model="searchForm.ruleType"
                  placeholder="请选择规则类型"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in ruleTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="分摊方法：">
                <el-select
                  v-model="searchForm.driverType"
                  placeholder="请选择分摊方法"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in driverTypeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </template>
          <!-- 显示隐藏区 -->
          <template slot="columnHide">
            <el-checkbox-group v-model="checkList">
              <el-checkbox
                v-for="item in textData"
                :label="item.label"
                :disabled="item.checkDisabled"
                :key="item.prop"
                >{{ item.label }}</el-checkbox
              >
            </el-checkbox-group>
          </template>
        </upper-template>

        <el-table 
        ref="multipleTable"
        :data="tableData"
        @row-click="rowClick"
        style="width: 100%">
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            v-for="(item, key) in showData"
            :key="key"
            :prop="item.prop"
            :label="item.label"
            :show-overflow-tooltip="true"
            :render-header="item.render"
            :sortable="item.sortable"
            :formatter="item.formatter"
            :width="item.width"
            :min-width="item.minwidth"
          ></el-table-column>
        </el-table>
        <pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          @refresh="searchFunc"
          :page-size="searchForm.size"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 新增编辑查看弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="saveTitles[operateType]"
      :visible.sync="addOrEdit"
      append-to-body
      width="65%"
      min-height="600px;"
      top="2%"
    >
      <!-- 引入公共组件 -->
      <ruleDefComponents
        :operateType="operateType"
        :ruleCode="ruleCode"
        @closeToQuery="closeToQuery"
        ref="childComponents"
      ></ruleDefComponents>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { ruleDefinition } from "@/api/index";
import upperTemplate from "@/components/upperTemplate.vue";
import ruleDefComponents from "@/components/ca/ruleDefComponents";
export default {
  components: {
    upperTemplate,
    ruleDefComponents,
  },
  data() {
    return {
      sceneCodeList:[],
      operateType: "1",
      ruleCode: "",
      driverTypeList: [
        {
          value: "D",
          label: "动态比例",
        },
        {
          value: "S",
          label: "静态比例",
        },
      ],
      ruleTypeList: [
        {
          value: "0",
          label: "机构层级",
        },
        {
          value: "1",
          label: "账户层级",
        },
      ],
      basicMsg: {}, // 基础信息回显
      treeName: "",
      addOrEdit: false, // 新增/编辑/查看弹窗
      isConfigDialog: false, // 配置层级弹窗
      serachMore: false, // 配置层级搜索是否收起
      isAddNextTree: false, // 添加下级树集弹窗
      operateType: 1, // 1:新增，2：编辑，3查看，5复制
      saveTitles: ["操作", "新增规则", "编辑规则", "查看规则","", "复制规则"],
      searchForm: {
        ruleCode: "",
        ruleName: "",
        ruleType: "",
        driverType: "",
        page: 1,
        size: 15,
      },
      total: 0,
      saveForm: {
        ruleCode: "",
        ruleName: "",
        ruleType: "",
        driverType: "",
      },
      saveFormRules: {
        ruleCode: [
          { required: true, message: "请输入层级树编码", trigger: "blur" },
        ],
        ruleName: [
          { required: true, message: "请输入层级树名称", trigger: "blur" },
          {
            pattern: /^[\u4E00-\u9FA5A-Za-z0-9（）()\[\]【】{}]{1,40}$/,
            message: "只能输入1-40位的汉字、字母、数字或括号",
            trigger: "blur"
          },
        ],
        ruleType: [
          { required: true, message: "请选择规则类型", trigger: "blur" },
        ],
      },
      checkList: [],
      // 完整表头字段&&列属性配置
      textData: [
        {
          prop: "ruleCode",
          label: "编码",
          sortable: true,
          align: "center",
          checkDisabled: true,
        },
        {
          prop: "ruleName",
          label: "名称",
          sortable: true,
          checkDisabled: true,
        },
        {
          prop: "ruleType",
          label: "规则类型",
          checkDisabled: false,
          formatter: (row) => {
            return this.$getLabel(row.ruleType, this.ruleTypeList);
          },
        },
        {
          prop: "driverType",
          label: "分摊方法",
          checkDisabled: false,
          formatter: (row) => {
            return this.$getLabel(row.driverType, this.driverTypeList);
          },
        },
        {
          prop: "sceneCode",
          label: "所属场景",
          checkDisabled: false,
        },
        {
          prop: "creator",
          label: "创建人",
          checkDisabled: false,
          formatter: (row) => {
            if (row.creator) {
              return row.creator;
            } else {
              return '-'
            }
          },
        },
        {
          prop: "createdTm",
          label: "创建时间",
          checkDisabled: false,
          formatter: (row) => {
            if (row.createdTm) {
              return moment(row.createdTm).format("YYYY-MM-DD HH:mm:ss"); // 24小时制
            } else{
              return '-'
            }
          },
        },
        {
          prop: "modifier",
          label: "修改人",
          checkDisabled: false,
          formatter: (row) => {
            if (row.modifier) {
              return row.modifier;
            } else {
              return '-'
            }
          },
        },
        {
          prop: "modifiedTm",
          label: "修改时间",
          checkDisabled: false,
          formatter: (row) => {
            if (row.modifiedTm) {
              return moment(row.modifiedTm).format("YYYY-MM-DD HH:mm:ss");
            } else {
              return '-'
            }
          },
        },
      ],
      // 获取table的数据
      tableData: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  created() {
    this.checkListInit();
    // this.getScenceList()
  },
  computed: {
    // 展示字段
    showData() {
      let arr = this.textData.map((v) => {
        return v.label;
      });
      let valArr = [],
        showData = [];
      // 选中的字段排序
      arr.forEach((element) => {
        let flag = false;
        this.checkList.forEach((e) => {
          if (e == element) {
            flag = true;
          }
        });
        if (flag) {
          valArr.push(element);
        }
      });
      // 控制表列隐藏显示
      for (let i = 0; i < this.checkList.length; i++) {
        for (let j = 0; j < this.textData.length; j++) {
          if (this.textData[j].label == valArr[i]) {
            let item = { ...this.textData[j] };
            showData.push(item);
          }
        }
      }
      return showData;
    },
  },
  mounted() {
    this.searchFunc();
  },
  watch: {},
  methods: {
      // 获取场景列表
    getScenceList() {
      ruleDefinition
        .ruleSceneComboAll()
        .then((res) => {
          if (res.code == 200) {
            this.sceneCodeList = res.datas;
          } else {
           this.$message.error(res.message);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 点击表格行事件
    rowClick(row){
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    checkListInit() {
      this.checkList = this.textData.map((v) => {
        return v.label;
      });
    },
    // 弹窗关闭调用查询
    closeToQuery(){
      this.addOrEdit = false;
      this.searchFunc()
    },
    // 新增
    addFunc() {
      this.operateType = "1";
      this.addOrEdit = true;
      this.ruleCode = "";
      this.$nextTick(()=>{
        this.$refs.childComponents.showTabInit();
      })
      // setTimeout(() => {
      //   this.$refs.childComponents.showTabInit();
      // }, 10);
    },
    // 搜索
    searchFunc() {
      let data = this.searchForm;
      console.log(data);
      ruleDefinition
        .ruleBaseQuery(data)
        .then((res) => {
          if (res.code == 200) {
            this.tableData = res.data.rows;
            this.total = res.data.total;
          } else{
            this.$message.error(res.message);
          }
        })
        .catch((err) => {});
    },
    // 编辑
    editFunc() {
      this.operateType = "2";
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行编辑");
      }
      let row = selection[0];
      this.ruleCode = row.ruleCode;
      this.addOrEdit = true;
      // setTimeout(() => {
      //   this.$refs.childComponents.showTabInit();
      // }, 10);
      this.$nextTick(()=>{
       this.$refs.childComponents.showTabInit();
      })
    },
    // 删除
    deleteFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("你确认要删除吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            ids: selection.map((v) => v.ruleCode),
          };
          ruleDefinition
            .ruleBaseRemove(params)
            .then((res) => {
              if (res.code == 200) {
                this.searchFunc();
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((err) => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
     // 运行
    running() {
      // 暂无接口
       let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行运行");
      }
      this.$confirm("你确认要运行吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            ruleCode: selection[0].ruleCode
          };
          ruleDefinition
            .ruleBaseRunRule(params)
            .then((res) => {
              if (res.code == 200) {
                this.$message.success(res.message);
                this.searchFunc();
              } else {
                this.$message.error(res.message);
              }
            })
            .catch((err) => {});
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // 查看
    viewFunc() {
      this.operateType = "3";
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行查看");
      }
      let row = selection[0];
      this.ruleCode = row.ruleCode;
      this.addOrEdit = true;
      // setTimeout(() => {
      //   this.$refs.childComponents.showTabInit();
      // }, 10);
      this.$nextTick(()=>{
         this.$refs.childComponents.showTabInit();
      })
    },
    // 复制
    copyView() {
      this.operateType = "5";
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行复制");
      }
      let row = selection[0];
      this.ruleCode = row.ruleCode;
      this.addOrEdit = true;
      // setTimeout(() => {
      //   this.$refs.childComponents.showTabInit();
      // }, 10);
      this.$nextTick(()=>{
         this.$refs.childComponents.showTabInit();
      })

    },
   
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    handleCurrentChange(val) {
      this.searchForm.page = val;
      console.log(`当前页: ${val}`);
      this.searchFunc();
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.el-dialog__body {
    max-height: 600px;
}
</style>